package com.cqggrw.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cqggrw.dao.RoleDaoI;
import com.cqggrw.domain.Role;
import com.cqggrw.util.DBUtil;

public class RoleDaoImpl implements RoleDaoI<Role> {

	public boolean add(Role t) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "insert into tbl_role(name, des, permValue) values(?, ?, ?);";
		int i = 0;
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, t.getName());
			ps.setString(2, t.getDes());
			ps.setInt(3, t.getPermValue());
			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1;
	}

	public boolean del(int id) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "delete from tbl_role where id = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1;
	}

	public boolean modify(Role t) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "update tbl_role set permValue = ? WHERE ID = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, t.getPermValue());
			ps.setInt(2, t.getId());
			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1;
	}

	public Role get(Role t) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "SELECT * FROM tbl_role where id = ?;";
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, t.getId());
			rs = ps.executeQuery();

			if (rs.next()) {
				t.setName(rs.getString("name"));
				t.setDes(rs.getString("des"));
				t.setPermValue(rs.getInt("permValue"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return t;
	}

	public List<Role> get() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Role role = null;
		List<Role> list = new ArrayList<Role>();
		
		String sql = "SELECT * FROM tbl_role;";
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();

			while (rs.next()) {
				role = new Role();
				role.setId(rs.getInt("id"));
				role.setName(rs.getString("name"));
				role.setDes(rs.getString("des"));
				role.setPermValue(rs.getInt("permValue"));
				list.add(role);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}


}
